package com.nerve.android.cloudoffice.app.group;

import org.nerve.android.NerveActivityGroup;
import org.nerve.android.annotation.Acvitity;
import org.nerve.android.annotation.NerveAnnotation;
import org.nerve.android.annotation.ViewOnId;

import android.annotation.SuppressLint;
import android.app.ActivityGroup;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nerve.android.cloudoffice.OfficeApplication;
import com.nerve.android.cloudoffice.R;
import com.nerve.android.cloudoffice.app.activity.AutoLoginActivity;
import com.nerve.android.cloudoffice.app.activity.SettingActivity;
import com.nerve.android.cloudoffice.app.activity.StartupActivity;
import com.nerve.android.cloudoffice.app.activity.chart.ChartActivity;
import com.nerve.android.cloudoffice.app.activity.customer.CustomerActivity;
import com.nerve.android.cloudoffice.app.activity.department.AddDepartmentActivity;
import com.nerve.android.cloudoffice.app.activity.department.AddUserActivity;
import com.nerve.android.cloudoffice.app.activity.department.DepartmentActivity;
import com.nerve.android.cloudoffice.app.activity.im.MessageActivity;
import com.nerve.android.cloudoffice.app.activity.notify.AddNotifyActivity;
import com.nerve.android.cloudoffice.app.activity.notify.NotifyActivity;
import com.nerve.android.cloudoffice.app.activity.task.AddTaskActivity;
import com.nerve.android.cloudoffice.app.activity.task.DepartmentTaskActivity;
import com.nerve.android.cloudoffice.app.activity.task.TaskActivity;
import com.nerve.android.cloudoffice.app.activity.task.TrashApplyActivity;
import com.nerve.android.cloudoffice.app.worker.LoadMessageWorkder;
import com.nerve.android.cloudoffice.app.worker.MessageLoadManager;
import com.nerve.android.cloudoffice.common.Const;
import com.nerve.android.cloudoffice.service.NetService;

/**
 * 
 * @project Cloudoffice GroupActivity.java
 * @datetime Aug 12, 2013 11:53:16 AM
 * @description 
 *    
 * @author 集成显卡 IBM 
 *			zxingming@qq.com
 *			zengxm@cn.ibm.com
 *
 * @change log:
 *
 */
@SuppressLint("HandlerLeak")
@Acvitity(layout=R.layout.app_main)
public class IndexGroupActivity extends ActivityGroup implements OnClickListener, NerveActivityGroup{

	//点击两次返回按钮时，可以退出程序
	private static final int DOUBLE_BACK_TIME = 2;
	
	public static final int HOME = 0;
	/**搜索菜单*/
	public static final int MESSAGE = 1;
	/**我的车票菜单*/
	public static final int SETTING = 2;
	
	public static final int DEPARTMENT = 3;
	
	public static final int NOTIFY = 4;
	
	public static final int TASK = 5;
	
	public static final int TRASH_APPLY = 6;
	
	public static final int CUSTOMER = 7;
	
	public static final int DEPARTMENT_TASK = 8;
	
	public static final int CHART = 9;
	
	private static final String[][] IDS = {
			{"startup"},
			{"myMessage"},
			{"setting"},
			{"department", "addDepartment", "addUser"},
			{"notifyList", "addNotify"},
			{"task", "addTask"},
			{"trashApply"},
			{"customer"},
			{"department_task", "taskActivity"},
			{"chart"}
		};
	
	private static final Class<?>[][] CLASS = {
		{StartupActivity.class},
		{MessageActivity.class},
		{SettingActivity.class},
		{DepartmentActivity.class, AddDepartmentActivity.class, AddUserActivity.class},
		{NotifyActivity.class, AddNotifyActivity.class},
		{TaskActivity.class, AddTaskActivity.class},
		{TrashApplyActivity.class},
		{CustomerActivity.class},
		{DepartmentTaskActivity.class, TaskActivity.class},
		{ChartActivity.class}
	};
	
	public static int MENU = 0;
	private static int INDEX[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
	
	@ViewOnId(id=R.id.BOTTOM_NAV)
	protected LinearLayout navLayout;
	@ViewOnId(id=R.id.nav_home, clickListener="this")
	protected TextView navHomeTV;
	@ViewOnId(id=R.id.nav_searchbus, clickListener="this")
	protected TextView navSearchTV;
	@ViewOnId(id=R.id.nav_myticket, clickListener="this")
	protected TextView navTicketTV;
	
	//最新消息显示器
	@ViewOnId(id=R.id.message_counter)
	protected TextView messageCounterTV;
	
	private LayoutParams params = null;
	
	@ViewOnId(id=R.id.CONTENT)
	protected ViewGroup contentLayout;
	
	protected View contentView; //主视图
	
	private long lastBackTime;
	private boolean isBackClick;//是否已经点击过一次返回了
	
	/*
	 * ==============================================================
	 * 相关组件
	 * ==============================================================
	 */
	private LoadMessageWorkder messageWorker;
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case LoadMessageWorkder.LOAD_MESSAGE_DONE:
				int oldCount = Integer.valueOf(messageCounterTV.getText().toString());
				oldCount += msg.arg1;
				messageCounterTV.setText(oldCount+"");
				
				messageCounterTV.setVisibility(oldCount > 0?View.VISIBLE:View.GONE);
				
				MessageLoadManager.messageLoadDone(msg.arg1);
				break;
			}
		}
	};
	/*
	 * ==============================================================
	 */
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		NerveAnnotation.parseActivity(this);
		
		params = new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		//changeActivity("search", SearchBusActivity.class);
		INDEX[MENU] = -1;
		next();
		Log.d("BUSActivity", "on Create!");
		
		resetCounter();
	}
	
	private void resetCounter(){
		messageCounterTV.setText("0");
		messageCounterTV.setVisibility(View.GONE);
	}
	
	/**
	 * @method name: startMessageWorker
	 * @description: 开启加载消息的线程
	 * @return type: void
	 *
	 */
	private void startMessageWorker(){
		messageWorker = new LoadMessageWorkder(
				OfficeApplication.getLoginId(), 
				handler, 
				Const.LOAD_MESSAGE_TIME
				);
		
		messageWorker.start();
		
		Const.log("----加载消息的工作者线程启动了！----");
	}
	
	/**
	 * save data
	 */
	@Override
	protected void onStop() {
		super.onStop();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		SharedPreferences sp = getSharedPreferences(AutoLoginActivity.SHARED_FILE, MODE_PRIVATE);
		Editor ed = sp.edit();
		OfficeApplication.JSESSIONID = NetService.getSessionId();
		ed.putString("JSESSIONID", OfficeApplication.JSESSIONID);
		ed.commit();
		
		Const.log("********saved JSESSIONID:"+OfficeApplication.JSESSIONID+"*********");
		Const.log("********IndexGroupActivity onDestroy!********");
		
		killMessageWorker();
	}

	@Override
	public void onClick(View v) {
		System.out.println("ok click。。。。");
		int index = -1;
		switch (v.getId()) {
		case R.id.nav_home:
			index = HOME;
			break;
		case R.id.nav_searchbus:
			index = MESSAGE;
			//转到我的消息页面时，清空计数器中的数据
			resetCounter();
			
			break;
		case R.id.nav_myticket:
			index = SETTING;
			break;
		}
		
		changeTab(index);
	}
	
	
	@Override
	public void changeTab(int index) {
		if(MENU == index)
			return;
		
		MENU = index;
		changeNav();
	}
	
	/**
	 * 更新底部导航
	 */
	public void changeNav(){
		/*
		if(MENU == BUS){
			changeActivity(IDS[MENU][INDEX[MENU]], CLASS[MENU][INDEX[MENU]], false);
		}else if(MENU == TICKET){
			changeActivity(IDS[MENU][INDEX[MENU]], CLASS[MENU][INDEX[MENU]], true);
		}else if(MENU == HOME){
			changeActivity(IDS[MENU][INDEX[MENU]], CLASS[MENU][INDEX[MENU]], false);
		}
		*/
		changeActivity(IDS[MENU][INDEX[MENU]], CLASS[MENU][INDEX[MENU]]);
		
		changeSelectBG();
	}
	
	private void changeSelectBG(){
		navTicketTV.setBackgroundResource(R.drawable.shape_bus_nav_bg_normal);
		navHomeTV.setBackgroundResource(R.drawable.shape_bus_nav_bg_normal);
		navSearchTV.setBackgroundResource(R.drawable.shape_bus_nav_bg_normal);
		
		if(MENU == MESSAGE){
			navSearchTV.setBackgroundResource(R.drawable.shape_bus_nav_bg_select);
		}else if(MENU == SETTING){
			navTicketTV.setBackgroundResource(R.drawable.shape_bus_nav_bg_select);
		}else if(MENU == HOME){
			navHomeTV.setBackgroundResource(R.drawable.shape_bus_nav_bg_select);
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		changeSelectBG();
		
		killMessageWorker();
		
		startMessageWorker();
	}
	
	private void killMessageWorker(){
		if(messageWorker != null){
			messageWorker.cancel();
			Thread temp = messageWorker;
			temp.interrupt();
			messageWorker = null;
		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
		Const.log("~~~~~~~~~~~~~应用暂停了！！~~~~~~~~~~~~~");
		
		/*
		if(messageWorker != null)
			messageWorker.cancel();
		*/
	}
	
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if(event.getKeyCode() == KeyEvent.KEYCODE_MENU){
			getCurrentActivity().dispatchKeyEvent(event);
			return true;
		}
		return super.dispatchKeyEvent(event);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Const.log("KEY DOWN!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		if(keyCode == KeyEvent.KEYCODE_BACK){
			System.out.println("back key pass！！！！！！！");
			if(INDEX[MENU] > 0)
				back();
			else{
				boolean showTip = false;
				
				if(!isBackClick){
					showTip = true;
				}else{
					//两次点击返回的时间超过指定的时间，无效
					if(System.currentTimeMillis() - lastBackTime > DOUBLE_BACK_TIME*1000){
						showTip = true;
					}else{
						finish();
						return false;
					}
				}
				
				if(showTip){
					isBackClick = true;
					lastBackTime = System.currentTimeMillis();
					Toast.makeText(getApplicationContext(), "再按一次退出本应用", DOUBLE_BACK_TIME*1000).show();
				}
			}
			return false;
		}
		else if(keyCode == KeyEvent.KEYCODE_MENU){
			return getCurrentActivity().onKeyDown(keyCode, event);
		}
		return super.onKeyDown(keyCode, event);
	}
	
	public void changeActivity(String name, Class<?> cls){
		Intent intent = new Intent(this, cls);
		contentView = getLocalActivityManager().startActivity(name, intent).getDecorView();
		contentLayout.removeAllViews();
		contentLayout.addView(contentView, params);
	}
	
	public void changeActivity(String name, Class<?> cls, boolean leftOut){
		boolean isFirst = (contentView == null);
		Intent intent = new Intent(this, cls);
		Animation anim = AnimationUtils.loadAnimation(this, leftOut?R.anim.left_out:R.anim.right_out);
		if(!isFirst)
			contentView.startAnimation(anim);
		contentView = getLocalActivityManager().startActivity(name, intent).getDecorView();
		
		contentLayout.removeAllViews();
		
		anim = AnimationUtils.loadAnimation(this, leftOut?R.anim.right_in:R.anim.left_in);
		if(!isFirst)
			contentView.startAnimation(anim);
		contentLayout.addView(contentView, params);
	}

	@Override
	public void next() {
		System.out.println("开始这个 Group：");
		try{
			if(INDEX[MENU] == IDS[MENU].length - 1)
				return ;
			INDEX[MENU] ++;
			String name = IDS[MENU][INDEX[MENU]];
			Class<?> clazz = CLASS[MENU][INDEX[MENU]];
			
			System.out.println("开始这个：" + name+",   " + clazz);
			
			changeActivity(name, clazz, true);
		}catch(Exception e){
			e.printStackTrace(System.out);
		}
	}
	
	@Override
	public void next(int step) {
		try{
			if(INDEX[MENU] + step >= IDS[MENU].length)
				return ;
			INDEX[MENU] += step;
			String name = IDS[MENU][INDEX[MENU]];
			Class<?> clazz = CLASS[MENU][INDEX[MENU]];
			
			System.out.println("开始这个：" + name+",   " + clazz);
			
			changeActivity(name, clazz, true);
		}catch(Exception e){
			e.printStackTrace(System.out);
		}
	}

	@Override
	public void back() {
		try{
			//为最底的activity时，直接返回
			if(INDEX[MENU] == 0)
				finish();
			INDEX[MENU] --;
			String name = IDS[MENU][INDEX[MENU]];
			Class<?> clazz = CLASS[MENU][INDEX[MENU]];
			
			changeActivity(name, clazz, false);
		}catch(Exception e){
			e.printStackTrace(System.out);
		}
	}

	@Override
	public void back(int step) {
		try{
			//为最底的activity时，直接返回
			if(INDEX[MENU] - step < 0)
				finish();
			INDEX[MENU] -= step;
			String name = IDS[MENU][INDEX[MENU]];
			Class<?> clazz = CLASS[MENU][INDEX[MENU]];
			
			changeActivity(name, clazz, false);
		}catch(Exception e){
			e.printStackTrace(System.out);
		}
	}
	public static void setMenu(int menu){
		if(menu < 0 || menu >= IDS.length)
			return ;
		MENU = menu;
	}

	@Override
	public void top() {
		try{
			INDEX[MENU] = 0;
			String name = IDS[MENU][INDEX[MENU]];
			Class<?> clazz = CLASS[MENU][INDEX[MENU]];
			
			changeActivity(name, clazz, false);
		}catch(Exception e){
			e.printStackTrace(System.out);
		}
	}
	
}